package future;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class FutureAPIDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        FutureTask<String> futureTask = new FutureTask<>(()->{
            System.out.println(Thread.currentThread().getName() + "\t ----come in");
            TimeUnit.SECONDS.sleep(5);
            return "task over";
        });
        Thread t1 = new Thread(futureTask, "t1");
        t1.start();

        System.out.println(Thread.currentThread().getName() + "\t ----忙其他任务了");

        while(true) {
            if(futureTask.isDone()) {
                System.out.println(futureTask.get());
                break;
            }else {
                System.out.println("正在处理中......");
                TimeUnit.SECONDS.sleep(1);
            }
        }
    }

    private static void m1() throws InterruptedException, ExecutionException, TimeoutException {
        FutureTask<String> futureTask = new FutureTask<>(()->{
            System.out.println(Thread.currentThread().getName() + "\t ----come in");
            TimeUnit.SECONDS.sleep(5);
            return "task over";
        });
        Thread t1 = new Thread(futureTask, "t1");
        t1.start();

        System.out.println(futureTask.get(3, TimeUnit.SECONDS)); //会阻塞等待结果

        System.out.println(Thread.currentThread().getName() + "\t ----忙其他任务了");
    }
}
